<template>
  <div class="page-apply">
    <div class="page-form">
      <LlForm ref="form" title="外出申请">
        <LlFormItem
          label="申请类型"
          filed="todoTypeName"
          :value="form.todoTypeName"
          :showArrow="false"
        />
        <LlFormItem
          label="执行人"
          filed="userName"
          :value="form.userName"
          :showArrow="false"
        />
        <LlFormItem
          :label="`${titlePrefix}时间段`"
          filed="outDate"
          :placehoder="`请选择${titlePrefix}时间段`"
          :value="outDate.length ? outDateString : null"
          :rules="[{ required: true, message: `请选择${titlePrefix}时间段` }]"
          @click="() => (showVisitTime = true)"
        >
          <template #icon>
            <Icon :name="DateIcon" />
          </template>
        </LlFormItem>
        <LlFormItem
          v-if="form.todoType !== 3"
          :label="`${titlePrefix}商机`"
          filed="businessOpportunityName"
          :value="form.businessOpportunityName"
          :showArrow="false"
        />
        <LlFormItem
          v-if="form.todoType !== 3"
          :label="`${titlePrefix}KP`"
          filed="kp"
          :value="form.kp"
          :rules="[{ required: true, message: `请选择${titlePrefix}KP` }]"
          @click="_showVisitKP"
        />
        <LlFormItem
          :label="`${titlePrefix}地点`"
          filed="address"
          :value="form.address"
          placehoder="请选择"
          :rules="[{ required: true, message: `请选择${titlePrefix}地点` }]"
          @click="() => (showVisitLocation = true)"
        >
          <template #icon>
            <Icon :name="LocationIcon" />
          </template>
        </LlFormItem>
        <LlFormItem
          :label="`${titlePrefix}内容`"
          filed="content"
          :show-arrow="false"
        >
          <Field
            v-model="form.content"
            rows="1"
            type="textarea"
            autosize
            class="!p-0"
            maxlength="150"
            placeholder="请输入内容"
            show-word-limit
          />
        </LlFormItem>
      </LlForm>
    </div>
    <div class="footer">
      <Button
        class="flex-1 !rounded-10px"
        @click="$router.back()"
        plain
        type="primary"
      >
        取消
      </Button>
      <Button
        @click="handleSave"
        :loading="loading"
        class="flex-1 !ml-9px !rounded-10px"
        type="primary"
      >
        申请
      </Button>
    </div>

    <!-- 外出时间  -->
    <Popup class="h-510px" v-model="showVisitTime" round position="bottom">
      <LlDateTimePicker
        title="外出时间"
        type="range"
        :allowSame="true"
        @cancel="showVisitTime = false"
        @confirm="_dateSelect"
      />
    </Popup>
    <!-- 拜访kp -->
    <Popup v-model="showVisitKP" round position="bottom">
      <Picker
        :columns="visitKPOptions"
        show-toolbar
        title="拜访KP"
        @cancel="showVisitKP = false"
        @confirm="(item) => _pickerSelect(item, 'kpId', 'kp', 'showVisitKP')"
        swipe-duration="100"
      />
    </Popup>
    <!-- 拜访地点 -->
    <Popup v-model="showVisitLocation" position="right">
      <LlMap
        v-if="showVisitLocation"
        @cancel="showVisitLocation = false"
        @confirm="_mapConfirm"
        type="search"
      />
    </Popup>
  </div>
</template>

<script>
import _ from "lodash";
import { Toast, Icon, Field, Button, Popup, Picker } from "vant";
import LlForm from "@/components/ll-form";
import LlFormItem from "@/components/ll-form-item";
import LlDateTimePicker from "@/components/ll-datetime-picker";
import LlMap from "@/components/ll-map";
import DateIcon from "@/assets/icon/date.png";
import LocationIcon from "@/assets/icon/location.png";
import { TODO_TYPE } from "@/constants";
import { fetchTodoDetail, fetchKpList, fetchTodoApply } from "@/services";

export default {
  components: {
    Icon,
    Field,
    Button,
    Popup,
    Picker,
    LlForm,
    LlFormItem,
    LlMap,
    LlDateTimePicker,
  },
  data() {
    return {
      DateIcon,
      LocationIcon,
      loading: false,
      form: {
        todoType: null,
        todoTypeName: null,
        userId: null,
        userName: null,
        outTimeBegin: null,
        outTimeEnd: null,
        businessOpportunityId: null, // 拜访商家
        businessOpportunityName: null, // 拜访商家名称
        kpId: null,
        kp: null,
        poi: null,
        address: null,
        content: null,
      },
      showVisitTime: false, // 外出时间
      showVisitMerchant: false, // 拜访商家
      merchantOptions: [],
      showVisitKP: false, // 拜访kp
      visitKPOptions: [
        { text: "kp1", key: 1 },
        { text: "kp2", key: 2 },
        { text: "kp3", key: 3 },
      ],
      showVisitLocation: false, // 拜访地点
    };
  },
  computed: {
    titlePrefix() {
      if (this.form.todoType) {
        const [type] = TODO_TYPE.filter(
          ({ key }) => key === this.form.todoType
        );
        return type.text;
      } else {
        return "拜访";
      }
    },
    outDateString() {
      let strat = this.outDate[0].slice(0, 16);
      let end = this.outDate[1].slice(0, 16);
      return strat + " 至 " + end;
    },
    outDate: {
      get() {
        const { outTimeBegin, outTimeEnd } = this.form;
        if (outTimeBegin && outTimeEnd) {
          return [outTimeBegin, outTimeEnd];
        } else {
          return [];
        }
      },
      set(val) {
        const [outTimeBegin, outTimeEnd] = val;
        this.form.outTimeBegin = outTimeBegin;
        this.form.outTimeEnd = outTimeEnd;
      },
    },
  },
  created() {
    this._initData();
  },
  methods: {
    _initData() {
      this.form.todoType = Number(this.$route.query.type);
      this.$nextTick(() => {
        this.handleApplyViews();
      });
    },
    // 获取申请详情
    async handleApplyViews() {
      try {
        const result = await fetchTodoDetail({ todoId: this.$route.query.id });
        const obj = {
          todoType: result.todoType,
          todoTypeName: `外出${this.titlePrefix}`,
          userId: result.userId, // 21657
          userName: result.username,
          outTimeBegin: null,
          outTimeEnd: null,
          businessOpportunityId: result.businessOpportunityId, // 拜访商家
          businessOpportunityName: result.businessOpportunityName, // 拜访商家名称
          kpId: result.kpId,
          kp: result.kpName,
          poi: result.poi,
          address: result.address,
          content: result.content,
        };
        this.form = { ...this.form, ...obj };
      } catch (error) {
        Toast("详情获取失败");
      }
    },
    handleSave: _.throttle(function () {
      this.$refs.form
        .validate()
        .then(async () => {
          try {
            const form = { ...this.form };
            // 扫街类型没有商家和KP
            if (this.form.todoType === 3) {
              form.businessOpportunityId = null;
              form.businessOpportunityName = null;
              form.kpId = null;
              form.kp = null;
            }
            this.loading = true;
            await fetchTodoApply({ id: this.$route.query.id, ...form });
            this.loading = false;
            Toast("申请成功");
            this.$store.commit(`work/${this.$route.query.load}`, {
              value: true,
            });
            this.$nextTick(() => {
              this.$router.back();
            });
          } catch (error) {
            this.loading = false;
            Toast("申请失败");
          }
        })
        .catch((e) => {
          Toast({ message: e[0].message, position: "top" });
        });
    }, 500),
    /**
     * 获取kp
     */
    async _showVisitKP() {
      try {
        const result = await fetchKpList({
          boId: this.form.businessOpportunityId,
        });
        this.visitKPOptions = result.map(({ name, id }) => ({
          text: name,
          key: id,
        }));
        this.$nextTick(() => {
          this.showVisitKP = true;
        });
      } catch (error) {
        Toast("KP加载失败");
      }
    },
    _dateSelect(val) {
      this.outDate = val;
      this.$nextTick(() => {
        this.showVisitTime = false;
      });
    },
    _pickerSelect(val, value, label, model) {
      this.form[value] = val.key;
      this.form[label] = val.text;
      this.$nextTick(() => {
        this[model] = false;
      });
    },
    _mapConfirm(poi) {
      this.form.address = `${poi.pname}${poi.cityname}${poi.adname}${poi.address}(${poi.name})`;
      this.form.poi = poi.id;
      this.$nextTick(() => {
        this.showVisitLocation = false;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page-apply {
  @apply flex flex-col;
  .page-form {
    @apply px-10px py-12px  flex-1 overflow-auto;
  }
  .footer {
    @apply flex items-center pt-10px px-16px bg-white;
    padding-bottom: calc(env(safe-area-inset-bottom) + 10px);
    box-shadow: 0px -2px 6px 0px rgba(164, 170, 183, 0.2);
  }
}
</style>
